package com.example.template.service.impl;

import com.example.template.common.base.impl.BaseServiceImpl;
import com.example.template.entity.Permission;
import com.example.template.entity.UserRole;
import com.example.template.mapper.RoleMapper;
import com.example.template.vo.MenuCardVO;
import com.example.template.vo.MenuVO;
import com.example.template.vo.TreeSelect;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.template.mapper.PermissionMapper;
import com.example.template.service.PermissionService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @className: PermissionServiceImpl
 * @description: TODO 类描述 
 * @author: Kuangkeli
 * @date: 2024/01/28 16:54
 **/

@Service
public class PermissionServiceImpl extends BaseServiceImpl<Permission> implements PermissionService{


    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RoleMapper roleMapper;

    /**
     * 根据用户ID获取菜单信息  （只包括目录和菜单  MC  不包括按钮）
     * @param userId
     * @return
     */
    @Override
    public Set<Permission> getMenuListByUserId(long userId) {
        UserRole userRole = roleMapper.findRolesByUserId(userId);
        Set<Permission> permissionList = null;
        if(userRole!=null && userRole.getRoles()!=null && userRole.getRoles().size()>0){
            permissionList = permissionMapper.getMenuByListRole(userRole.getRoles());
        }
        return permissionList;
    }

    @Override
    public Set<Long> getPermIdsByRoleId(long roleId) {
        Set<Long> perIds = permissionMapper.getPermsByRoleId(roleId);
        return perIds;
    }

    /**
     * 根据用户ID 获取权限参数列表
     * @param userId
     * @return
     */
    @Override
    public List<String> getPermsListByUserId(long userId) {
        Set<Permission> permissionList = getPermissionListByUserId(userId);
        if(permissionList!=null && permissionList.size()>0){
            List<String> permissionNameList = new LinkedList<>();
            for(Permission permission:permissionList){
                permissionNameList.add(permission.getPerms());
            }
            return permissionNameList;
        }
        return null;
    }

    /**
     * 获取权限列表   获取所有的权限信息
     * @param userId
     * @return
     */
    @Override
    public Set<Permission> getPermissionListByUserId(long userId) {
        UserRole userRole = roleMapper.findRolesByUserId(userId);
        Set<Permission> permissionList = null;
        if(userRole!=null && userRole.getRoles()!=null && userRole.getRoles().size()>0){
            permissionList = permissionMapper.getPemissionsByListRole(userRole.getRoles());
        }
        return permissionList;
    }

    @Override
    public List<MenuCardVO> getMenuTreeByUserId(long userId) {
        List<MenuCardVO> menuCardVOList = new ArrayList<>();
        UserRole userRole = roleMapper.findRolesByUserId(userId);
        List<Permission> parentMenuSet = null;
        if(userRole!=null && userRole.getRoles()!=null && userRole.getRoles().size()>0){
           parentMenuSet = permissionMapper.getParentMenuByListRole(userRole.getRoles());
        }
        //循环父目录找子菜单
        for (Permission p:parentMenuSet) {
            MenuCardVO menuCardVO = new MenuCardVO();
            Set<MenuVO> sonMenuVOSet = new HashSet<>();
            menuCardVO.setTitle(p.getMenuName());
            Set<Permission> sonMenuSet = permissionMapper.getMenuByPid(p.getMenuId(),userRole.getRoles());
            for (Permission sp: sonMenuSet) {
                MenuVO e = new MenuVO();
                BeanUtils.copyProperties(sp,e);
                sonMenuVOSet.add(e);
            }
            menuCardVO.setMenuVOList(sonMenuVOSet);
            menuCardVOList.add(menuCardVO);
        }
        return menuCardVOList;
    }


    /**
     * 根据父节点的ID获取所有子节点
     * @param list 分类表
     * @param parentId 传入的父节点ID
     * @return String
     */
    public List<Permission> getChildPerms(List<Permission> list, int parentId)
    {
        List<Permission> returnList = new ArrayList<Permission>();
        for (Iterator<Permission> iterator = list.iterator(); iterator.hasNext();)
        {
            Permission t = (Permission) iterator.next();
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId() == parentId)
            {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    /**
     * 递归列表
     *
     * @param list 分类表
     * @param t 子节点
     */
    private void recursionFn(List<Permission> list, Permission t)
    {
        // 得到子节点列表
        List<Permission> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Permission tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<Permission> getChildList(List<Permission> list, Permission t)
    {
        List<Permission> tlist = new ArrayList<Permission>();
        Iterator<Permission> it = list.iterator();
        while (it.hasNext())
        {
            Permission n = (Permission) it.next();
            if (n.getParentId().longValue() == t.getMenuId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<Permission> list, Permission t)
    {
        return getChildList(list, t).size() > 0;
    }


    /**
     * 构建前端所需要树结构
     *
     * @param menus 菜单列表
     * @return 树结构列表
     */
    @Override
    public List<Permission> buildMenuTree(List<Permission> menus)
    {
        List<Permission> returnList = new ArrayList<Permission>();
        List<Long> tempList = menus.stream().map(Permission::getMenuId).collect(Collectors.toList());
        for (Iterator<Permission> iterator = menus.iterator(); iterator.hasNext();)
        {
            Permission menu = (Permission) iterator.next();
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId()))
            {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty())
        {
            returnList = menus;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param menus 菜单列表
     * @return 下拉树结构列表
     */
    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<Permission> menus)
    {
        List<Permission> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public List<Permission> selectAll() {
        return permissionMapper.selectAll();
    }

}
